package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.acct.facade.response.VirtAcctTransStatusQueryResponse;
import cc.rengu.igas.acct.facade.result.Result;
import cc.rengu.igas.bsps.common.constant.BspsAppParamConstant;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.oltp.service.base.DubboAsynBaseService;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.dao.MchntOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.PayOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.UserOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.MchntOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.PayOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.UserOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.MchntOrderInfo;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.BizStatusEnum;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.utility.annotation.BIZ_PROCESS;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 虚拟账户记账状态查询异步处理
 */
public class AsynVirtAcctTransStatusQueryService extends DubboAsynBaseService {
    @BIZ_PROCESS
    private void virtAcctMultiMchntAdjust() throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        String instId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID);
        String mchntNo = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.MCHNT_NO);
        /*判断记账结果，更新支付订单状态*/
        Result<VirtAcctTransStatusQueryResponse> result = new Result<>();
        ConvertUtil.convertOutput(result);
        VirtAcctTransStatusQueryResponse response = result.getResult();
        /*根据渠道标识、商户订单号查询交易*/
        OrderService orderService = new OrderServiceImpl();
        UserOrderInfoMapper userOrderInfoMapper = new UserOrderInfoMapperImpl();
        UserOrderInfo userOrderInfo = userOrderInfoMapper.selectUserOrderInfoByPrimaryKey(instId, sysSeqNum);
        if (userOrderInfo == null) {
            rglog.info("用户支付订单不存在");
            return;
        }

        /*查询商户支付订单列表*/
        MchntOrderInfoMapper mchntOrderInfoMapper = new MchntOrderInfoMapperImpl();
        MchntOrderInfo mchntOrderInfo = mchntOrderInfoMapper.selectMchntOrderInfoByPrimaryKey(instId, userOrderInfo.getSysSeqNum(), mchntNo);
        if (mchntOrderInfo == null) {
            rglog.info("商户订单信息表中无该笔商户支付订单,instId:<{}>,sysSeqNum:<{}>.", instId, userOrderInfo.getSysSeqNum());
            /*更新订单表状态为失败*/
            userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
            userOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));

            if (!orderService.updateOrderInfo(userOrderInfo, null, null)) {
                rglog.error("更新订单表状态失败");
            }
            return;
        }

        PayOrderInfoMapper payOrderInfoMapper = new PayOrderInfoMapperImpl();
        /*获取支付订单列表*/
        List<PayOrderInfo> payOrderInfoList = payOrderInfoMapper.selectPayOrderInfoBySysSeqNum(instId, userOrderInfo.getSysSeqNum());
        if (payOrderInfoList == null || payOrderInfoList.size() == 0) {
            rglog.error("根据机构号<{}>、系统流水号<{}>获取支付订单列表失败", instId, userOrderInfo.getSysSeqNum());
            return;
        }
        List<PayOrderInfo> payOrderInfoListAcct = payOrderInfoList.stream().filter(item -> item.getMsgDstId().equals(ChannelEnum.ACCT.getChannelType())).collect(Collectors.toList());
        if (payOrderInfoListAcct == null || payOrderInfoListAcct.size() != 1) {
            return;
        }
        PayOrderInfo payOrderInfoAcct = payOrderInfoListAcct.get(0);
        /*判断查询结果，更新状态*/
        if (!result.isSuccess() || !BspsAppParamConstant.DUBBO_SUCCESS.equals(response.getRespCode())) {
            rglog.error("虚拟账户查询状态接口调用失败");
            updateFailOrderStatus(userOrderInfo, mchntOrderInfo, payOrderInfoAcct);
            return;
        } else {
            if (!"00".equals(response.getTransStatus())) {
                /*TODO 记账失败，调用冲正*/
                coreRevsal();
                updateFailOrderStatus(userOrderInfo, mchntOrderInfo, payOrderInfoAcct);
                return;
            }
        }
        userOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
        userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
        userOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));

        mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
        mchntOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
        mchntOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));

        payOrderInfoAcct.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
        payOrderInfoAcct.setBizStatus(BizStatusEnum.FINISH.getStatus());
        payOrderInfoAcct.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        if (!orderService.updateOrderInfo(userOrderInfo, Arrays.asList(mchntOrderInfo), payOrderInfoAcct)) {
            rglog.error("更新订单表状态失败");
            throw new BizException(RespCodeEnum.TRANS_IN_PROGRESS.getRespCode(), RespCodeEnum.TRANS_IN_PROGRESS.getRespDesc());
        }
        /*记账成功后，调用微信消息推送*/

    }

    /* TODO 核心记账冲正*/
    void coreRevsal() {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        try {
//            QuickPayDebitCardBankRequest quickPayDebitCardBankRequest = (QuickPayDebitCardBankRequest)
//                    xmlTreeUtil.getXmlTreeObjectValue("quickPayDebitCardBankRequest",QuickPayDebitCardBankRequest.class);
//            cc.rengu.igas.channel.esb.facade.base.Header esbHeader = quickPayDebitCardBankRequest.getHeader();
        } catch (Exception e) {
            rglog.error(e.getMessage());
        }
    }

    Boolean updateFailOrderStatus(UserOrderInfo userOrderInfo, MchntOrderInfo mchntOrderInfo, PayOrderInfo payOrderInfo) throws Exception {
        OrderService orderService = new OrderServiceImpl();
        /*更新订单表状态为失败*/
        userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
        userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
        userOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));

        mchntOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
        mchntOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
        mchntOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));

        payOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
        payOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
        payOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        if (!orderService.updateOrderInfo(userOrderInfo, Arrays.asList(mchntOrderInfo), payOrderInfo)) {
            rglog.error("更新订单表状态失败");
            return false;
        }
        return true;
    }
}
